<script setup>
import {ref, onMounted, computed} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { orderAPI } from '@/api/order.js'

const router = useRouter()
const route = useRoute()

// 响应式数据
const orders = ref([])
const loading = ref(false)
const activeTab = ref('all') // 全部、待接单、配送中、已完成
const navTab = ref('orders') // 导航栏高亮：home、orders、data、profile
const selectedOrder = ref(null)
const businessInfo = JSON.parse(sessionStorage.getItem('business') || '{}')
const businessName = ref(businessInfo.businessName || '')

// 订单状态映射（从1开始编号，支付后的状态）
const orderStatusMap = {
  1: { text: '待接单', color: '#ff9800', class: 'pending' },
  2: { text: '配送中', color: '#673ab7', class: 'delivering' },
  3: { text: '已完成', color: '#4caf50', class: 'completed' },
  4: { text: '已取消', color: '#f44336', class: 'cancelled' },
  5: { text: '已拒绝', color: '#9e9e9e', class: 'rejected' }
}

// 获取当前商家ID
const getCurrentBusinessId = () => {
  const businessInfo = JSON.parse(sessionStorage.getItem('business') || '{}')
  return businessInfo.id || businessInfo.businessId || '1'
}

// 加载单个订单的详细信息
const loadOrderDetail = async (orderId) => {
  try {
    const response = await orderAPI.getOrderById(orderId)

    if (response.data && response.data.data) {
      const orderDetailData = response.data.data
      console.log(`订单 ${orderId} 详情:`, orderDetailData)

      return {
        orderDetails: Array.isArray(orderDetailData)
            ? orderDetailData.map(detail => ({
              ...detail,
              food: detail.food || detail.data?.food || null
            }))
            : [],
        business: orderDetailData.business || null,
        orderTotal: orderDetailData.orderTotal || 0,
        orderDate: orderDetailData.orderDate || null
      }
    }
    return null
  } catch (error) {
    console.error(`加载订单 ${orderId} 详情失败:`, error)
    return null
  }
}

// 加载订单列表
const loadOrders = async () => {
  try {
    loading.value = true
    const businessId = getCurrentBusinessId()
    const response = await orderAPI.listOrdersByBusinessId(businessId)

    if (response.data && response.data.success) {
      const ordersData = response.data.data || response.data
      // 过滤掉状态为0（未支付）的订单，只显示支付后的订单
      const filteredOrders = (Array.isArray(ordersData) ? ordersData : [])
          .filter(order => order.orderState !== 0) // 排除未支付订单

      // 并行加载所有订单的详情
      const ordersWithDetails = await Promise.all(
          filteredOrders.map(async (order) => {
            try {
              // 加载订单详情
              const detailData = await loadOrderDetail(order.id)

              return {
                ...order,
                // 合并详情数据
                orderDetails: detailData?.orderDetails || order.orderDetails || [],
                business: detailData?.business || order.business || {},
                orderTotal: detailData?.orderTotal || order.orderTotal || 0,
                orderDate: detailData?.orderDate || order.orderDate,
                // 确保使用快照数据
                showDetail: false // 初始不显示详情
              }
            } catch (error) {
              console.error(`处理订单 ${order.id} 失败:`, error)
              return {
                ...order,
                orderDetails: order.orderDetails || [],
                business: order.business || {},
                showDetail: false
              }
            }
          })
      )

      // 按时间倒序排列
      orders.value = ordersWithDetails.sort((a, b) =>
          new Date(b.updateTime || b.orderDate) - new Date(a.updateTime || a.orderDate)
      )

      console.log('加载的订单详情:', orders.value)
    } else {
      orders.value = []
    }
  } catch (error) {
    console.error('加载订单失败:', error)
    orders.value = []
    showNotification('加载订单失败')
  } finally {
    loading.value = false
  }
}

// 过滤订单
const filteredOrders = computed(() => {
  if (activeTab.value === 'all') {
    return orders.value
  }

  const statusMap = {
    'pending': 1,    // 待接单
    'delivering': 2, // 配送中
    'completed': 3   // 已完成
  }

  const targetStatus = statusMap[activeTab.value]
  return orders.value.filter(order => order.orderState === targetStatus)
})

// 接受订单
const acceptOrder = async (order) => {
  if (!confirm('确定要接受这个订单吗？')) {
    return
  }

  try {
    const response = await orderAPI.updateOrderState(order.id, 2) // 2表示配送中

    if (response.data && response.data.success) {
      showNotification('订单接受成功')
      loadOrders() // 重新加载订单列表
    } else {
      throw new Error(response.data?.message || '操作失败')
    }
  } catch (error) {
    console.error('接受订单失败:', error)
    showNotification(error.message || '接受订单失败')
  }
}

// 拒绝订单
const rejectOrder = async (order) => {
  if (!confirm('确定要拒绝这个订单吗？')) {
    return
  }

  try {
    const response = await orderAPI.updateOrderState(order.id, 5) // 5表示已拒绝

    if (response.data && response.data.success) {
      showNotification('订单已拒绝')
      loadOrders() // 重新加载订单列表
    } else {
      throw new Error(response.data?.message || '操作失败')
    }
  } catch (error) {
    console.error('拒绝订单失败:', error)
    showNotification(error.message || '拒绝订单失败')
  }
}

// 标记为已完成
const markAsCompleted = async (order) => {
  try {
    const response = await orderAPI.updateOrderState(order.id, 3) // 3表示已完成

    if (response.data && response.data.success) {
      showNotification('订单已完成')
      loadOrders()
    } else {
      throw new Error(response.data?.message || '操作失败')
    }
  } catch (error) {
    console.error('完成订单失败:', error)
    showNotification(error.message || '完成订单失败')
  }
}

// 显示订单详情
const showOrderDetails = (order) => {
  selectedOrder.value = selectedOrder.value?.id === order.id ? null : order
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
  } catch (error) {
    return timeString
  }
}

// 格式化金额
const formatPrice = (price) => {
  const num = Number(price)
  if (isNaN(num)) {
    return '¥0.00'
  }
  return `¥${num.toFixed(2)}`
}

// 获取显示用的商品名称（优先使用快照）
const getDisplayFoodName = (foodItem) => {
  return foodItem?.foodNameSnapshot || foodItem?.foodName || foodItem?.food?.foodName || '未知商品'
}

// 获取显示用的商品价格（优先使用快照）
const getDisplayFoodPrice = (foodItem) => {
  const price = foodItem?.foodPriceSnapshot || foodItem?.foodPrice || foodItem?.food?.foodPrice
  // console.log( foodItem?.foodPriceSnapshot)
  return Number(price) || 0
}

// 获取显示用的配送价格（优先使用快照）
const getDisplayDeliveryPrice = (order) => {
  const price = order?.orderDetails[0].deliverPrinceSnapshot || order?.deliveryPrice || order?.business?.deliveryPrice
  console.log(order)
  return Number(price) || 0
}

// 计算订单总价（使用快照数据）
const calculateTotal = (order) => {
  // 如果有订单详情数据，使用详情计算
  if (order.orderDetails && order.orderDetails.length > 0) {
    const foodTotal = order.orderDetails.reduce((sum, detail) => {
      const price = getDisplayFoodPrice(detail)
      const quantity = detail.quantity || 0
      return sum + (price * quantity)
    }, 0)
    const deliveryPrice = getDisplayDeliveryPrice(order)
    return foodTotal + deliveryPrice
  }

  // 如果没有详情数据，使用订单总额
  return Number(order.orderTotal) || 0
}

// 获取订单商品列表（兼容多种数据结构）
const getOrderFoods = (order) => {
  // 优先使用orderDetails
  if (order.orderDetails && order.orderDetails.length > 0) {
    return order.orderDetails.map(detail => ({
      foodId: detail.foodId || detail.id,
      foodName: getDisplayFoodName(detail),
      foodPrice: getDisplayFoodPrice(detail),
      quantity: detail.quantity || 0
    }))
  }

  // 其次使用foods数组
  if (order.foods && order.foods.length > 0) {
    return order.foods.map(food => ({
      foodId: food.foodId || food.id,
      foodName: getDisplayFoodName(food),
      foodPrice: getDisplayFoodPrice(food),
      quantity: food.quantity || 0
    }))
  }

  return []
}

// 通知功能
const showNotification = (message) => {
  const notification = document.createElement('div')
  notification.className = 'global-notification'
  notification.textContent = message
  notification.style.cssText = `
    position: fixed;
    top: 60px;
    left: 50%;
    transform: translateX(-50%);
    padding: 12px 20px;
    background-color: #4caf50;
    color: white;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 300;
    animation: slideIn 0.3s, fadeOut 0.5s 2.5s;
  `

  document.body.appendChild(notification)

  setTimeout(() => {
    if (notification.parentNode) {
      notification.parentNode.removeChild(notification)
    }
  }, 3000)
}

// 导航功能
const goBack = () => {
  router.go(-1)
}

const setActiveTab = (tab) => {
  navTab.value = tab
  // 根据tab跳转到不同页面
  switch (tab) {
    case 'home':
      router.push('/BusinessEnd')
      break
    case 'orders':
      // 当前页面
      break
    case 'data':
      router.push('/business-data')
      break
    case 'profile':
      router.push('/business-profile')
      break
  }
}

// 生命周期
onMounted(() => {
  loadOrders()
  const urlParams = new URLSearchParams(window.location.search)
  const tab = urlParams.get('tab')
  if (tab && ['all', 'pending', 'delivering', 'completed'].includes(tab)) {
    activeTab.value = tab
  }
})
</script>

<template>
  <div class="orders-container">
    <!-- 顶部导航栏 -->
    <div class="top-bar">
      <div class="back-btn" @click="goBack">
        <i class="fas fa-arrow-left"></i>
      </div>
      <div class="page-title">订单管理({{businessName}})</div>
      <div class="top-icon" @click="setActiveTab('pending')">
        <i class="fas fa-bell"></i>
        <div class="notification-badge">{{ orders.filter(order => order.orderState === 1).length }}</div>
      </div>
    </div>

    <!-- 订单状态筛选 -->
    <div class="filter-tabs">
      <div
          class="filter-tab"
          :class="{ active: activeTab === 'all' }"
          @click="setActiveTab('all')"
      >
        全部
      </div>
      <div
          class="filter-tab"
          :class="{ active: activeTab === 'pending' }"
          @click="setActiveTab('pending')"
      >
        待接单
        <span class="badge" v-if="orders.filter(order => order.orderState === 1).length > 0">
          {{ orders.filter(order => order.orderState === 1).length }}
        </span>
      </div>
      <div
          class="filter-tab"
          :class="{ active: activeTab === 'delivering' }"
          @click="setActiveTab('delivering')"
      >
        配送中
      </div>
      <div
          class="filter-tab"
          :class="{ active: activeTab === 'completed' }"
          @click="setActiveTab('completed')"
      >
        已完成
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="orders-list">
      <div v-if="loading" class="loading">
        <i class="fas fa-spinner fa-spin"></i> 加载订单中...
      </div>

      <div v-else-if="filteredOrders.length === 0" class="empty-state">
        <i class="fas fa-clipboard-list"></i>
        <p>暂无订单</p>
      </div>

      <div v-else class="orders-content">
        <div
            v-for="order in filteredOrders"
            :key="order.id"
            class="order-item"
            :class="orderStatusMap[order.orderState]?.class"
        >
          <div class="order-header" @click="showOrderDetails(order)">
            <div class="order-info">
              <div class="order-number">订单号: {{ order.orderId || order.id }}</div>
              <div class="order-time">{{ formatTime(order.orderDate) }}</div>
            </div>
            <div class="order-status" :style="{ color: orderStatusMap[order.orderState]?.color }">
              {{ orderStatusMap[order.orderState]?.text }}
            </div>
          </div>

          <div class="order-content">
            <div class="customer-info">
              <i class="fas fa-user"></i>
              {{ order.customer?.username || order.userName || '顾客' }}
              <span class="customer-phone">{{ order.phone || order.userPhone }}</span>
            </div>

            <div class="order-foods">
              <div v-for="food in getOrderFoods(order)" :key="food.foodId" class="food-item">
                <span class="food-name">{{ food.foodName }}</span>
                <span class="food-quantity">×{{ food.quantity }}</span>
                <span class="food-price">{{ formatPrice(food.foodPrice) }}</span>
              </div>
            </div>

            <div class="order-total">
              <div class="total-line">
                <span>商品总额:</span>
                <span>{{ formatPrice(calculateTotal(order)) }}</span>
              </div>
              <div class="total-line">
                <span>配送费:</span>
                <span>{{ formatPrice(getDisplayDeliveryPrice(order)) }}</span>
              </div>
              <div class="total-line total">
                <span>实付:</span>
                <span class="total-price">{{ formatPrice(calculateTotal(order)) }}</span>
              </div>
            </div>
          </div>

          <!-- 订单操作按钮 -->
          <div class="order-actions" v-if="order.orderState === 1">
            <button class="btn btn-reject" @click="rejectOrder(order)">
              <i class="fas fa-times"></i>拒绝
            </button>
            <button class="btn btn-accept" @click="acceptOrder(order)">
              <i class="fas fa-check"></i>接受
            </button>
          </div>

          <div class="order-actions" v-else-if="order.orderState === 2">
            <button class="btn btn-complete" @click="markAsCompleted(order)">
              <i class="fas fa-flag-checkered"></i>完成订单
            </button>
          </div>

          <!-- 订单详情 -->
          <div v-if="selectedOrder?.id === order.id" class="order-details">
            <div class="detail-section">
              <h4>配送信息</h4>
              <p><i class="fas fa-map-marker-alt"></i> {{ order.deliveryAddress?.address || order.address || '暂无地址信息' }}</p>
              <p v-if="order.userRemark || order.remark"><i class="fas fa-comment"></i> 顾客备注: {{ order.userRemark || order.remark }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div
          class="bottom-btn"
          :class="{ active: navTab === 'home' }"
          @click="setActiveTab('home')"
      >
        <i class="fas fa-home"></i>
        <span>首页</span>
      </div>

      <div
          class="bottom-btn"
          :class="{ active: navTab === 'orders' }"
          @click="setActiveTab('orders')"
      >
        <i class="fas fa-clipboard-list"></i>
        <span>订单</span>
      </div>

      <div
          class="bottom-btn"
          :class="{ active: navTab === 'data' }"
          @click="setActiveTab('data')"
      >
        <i class="fas fa-chart-line"></i>
        <span>数据</span>
      </div>

      <div
          class="bottom-btn"
          :class="{ active: navTab === 'profile' }"
          @click="setActiveTab('profile')"
      >
        <i class="fas fa-user"></i>
        <span>我的</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.orders-container {
  display: flex;
  flex-direction: column;
  margin: 0 auto;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 70px;
  position: relative;
  overflow: visible;
}

/* 顶部导航 */
.top-bar {
  position: sticky;
  top: 0;
  width: 100%;
  //max-width: 360px;
  height: 50px;
  background: linear-gradient(90deg, #0088ff, #00bbff);
  color: white;
  display: flex;
  align-items: center;
  padding: 0 15px;
  z-index: 9998;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.back-btn {
  font-size: 18px;
  margin-right: 15px;
  cursor: pointer;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  flex: 0.9;
}

.top-icon {
  font-size: 18px;
  position: relative;
}

.notification-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background-color: #ff5252;
  color: white;
  font-size: 10px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 筛选标签 */
.filter-tabs {
  display: flex;
  background: white;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 50px;
  z-index: 90;
}

.filter-tab {
  flex: 1;
  text-align: center;
  padding: 15px 10px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
}

.filter-tab.active {
  color: #0097ff;
  border-bottom-color: #0097ff;
  font-weight: 600;
}

.filter-tab .badge {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #ff5252;
  color: white;
  font-size: 10px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 订单列表 */
.orders-list {
  padding: 15px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #0097ff;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #777;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 15px;
  color: #ddd;
}

.order-item {
  background: white;
  border-radius: 12px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.order-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.order-info {
  flex: 1;
}

.order-number {
  font-weight: 600;
  font-size: 15px;
  margin-bottom: 5px;
}

.order-time {
  font-size: 12px;
  color: #999;
}

.order-status {
  font-size: 14px;
  font-weight: 600;
}

.order-content {
  padding: 15px;
}

.customer-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #333;
}

.customer-info i {
  margin-right: 8px;
  color: #0097ff;
}

.customer-phone {
  margin-left: 15px;
  color: #666;
  font-size: 13px;
}

.order-foods {
  margin-bottom: 15px;
}

.food-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  font-size: 14px;
}

.food-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 10px;
}

.food-quantity {
  color: #666;
  margin-right: 10px;
}

.food-price {
  color: #ff5339;
  font-weight: 500;
}

.order-total {
  border-top: 1px dashed #eee;
  padding-top: 10px;
}

.total-line {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
  font-size: 14px;
}

.total-line.total {
  font-weight: 600;
  font-size: 16px;
  margin-top: 5px;
  padding-top: 5px;
  border-top: 1px solid #eee;
}

.total-price {
  color: #ff5339;
}

/* 订单操作按钮 */
.order-actions {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 10px;
}

.btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.btn:active {
  transform: translateY(1px);
}

.btn-reject {
  background: #ffebee;
  color: #f44336;
}

.btn-accept {
  background: #e8f5e8;
  color: #4caf50;
}

.btn-delivering {
  background: #e3f2fd;
  color: #2196f3;
}

.btn-complete {
  background: #f3e5f5;
  color: #9c27b0;
}

/* 订单详情 */
.order-details {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
  font-size: 14px;
}

.detail-section p {
  margin-bottom: 8px;
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
}

.detail-section i {
  margin-right: 8px;
  color: #0097ff;
  width: 16px;
}

/* 底部操作栏 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  width: 100%;
  height: 60px;
  background-color: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 9999;
  transform: translateZ(0);
  -webkit-transform: translateZ(0);
}

.bottom-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 8px;
  color: #666;
  font-size: 12px;
  text-align: center;
  transition: color 0.2s;
  cursor: pointer;
}

.bottom-btn i {
  font-size: 20px;
  margin-bottom: 3px;
}

.bottom-btn.active {
  color: #0097ff;
}

.bottom-btn:active {
  transform: scale(0.95);
}

/* 动画 */
@keyframes slideIn {
  from {
    top: 0;
    opacity: 0;
  }
  to {
    top: 60px;
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
</style>